import axios from 'axios';

const checkLogin = ( callback:Function ) => {

    // todo 首先从url 中获取 token，再考虑 localStorage
    
    const token:string|null = localStorage.getItem('token');
    let url:any = window.VITE_URL + '/admin.user/check';
    // let url:any = process.env.VUE_APP_URL + '/api/check/login';
    url += '?token=' + token;
    axios.get( url ).then(res=>{

        if( typeof callback == 'function' ){
            callback( res.data );
        }

    });


}

// 检查是否为微擎环境， 若是，把返回的token 存储到localstorage中， 方便后续调用
const checkWQLogin =  ( callback:Function ) => {

    // todo 从url 中获取 user_id, uniacid 参数
    const location_url = new URL(window.location.href); // 或者你可以直接传入一个URL字符串 
    const user_id = location_url.searchParams.get('user_id'); // "John" 
    const uniacid = location_url.searchParams.get('uniacid'); // "30" 

    console.log(user_id, uniacid);
    let url:any = window.VITE_URL + '/admin.user/wq_check';
    url += '?user_id=' + user_id;
    url += '&uniacid=' + uniacid;
    axios.get( url ).then( ( res:any ) => {

        if( res.data.token ){
            localStorage.setItem('token', res.data.token );

            // 删除掉参数，以免无法退出
            // const params = new URLSearchParams(location_url.search);
            // params.delete('user_id');
            // params.delete('uniacid');
            // location_url.search = params.toString();
        }
        if( typeof callback == 'function' ){
            callback( res.data );
        }

    });

}
export { checkLogin, checkWQLogin }
export default checkLogin;